package com.zr.d_c.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.zr.d_c.model.Role;
import com.zr.d_c.model.Seller;
import com.zr.d_c.model.User;
import com.zr.d_c.service.OrderService;
import com.zr.d_c.service.RoleService;
import com.zr.d_c.service.SellerService;
import com.zr.d_c.service.UserInfoService;
import com.zr.d_c.service.UserService;
import com.zr.d_c.serviceimpl.OrderServiceImpl;
import com.zr.d_c.serviceimpl.RoleServiceImpl;
import com.zr.d_c.serviceimpl.SellerServiceImpl;
import com.zr.d_c.serviceimpl.UserInfoServiceImpl;
import com.zr.d_c.serviceimpl.UserServiceImpl;

import net.sf.json.JSONObject;
/**
 * 登陆
 * @author Administrator
 *
 */
public class LoginController extends HttpServlet {

	UserInfoService loginserivce = new UserInfoServiceImpl();
	UserService userservice = new UserServiceImpl();
	RoleService roleservice = new RoleServiceImpl();
	SellerService sellerservice = new SellerServiceImpl();
	OrderService orderservice = new OrderServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = req.getSession();
		String uname = req.getParameter("uname");
		String upsw = req.getParameter("upsw");
		User u = userservice.getUserByUnameAndUpsw(uname, upsw);
		if(u != null){
			session.setAttribute("currentUser", u);
			session.setAttribute("errorMsg", "");
			int rid = u.getRid();
			Role r = roleservice.getRoleByRid(rid);
			String currentUserName = loginserivce.getCurrentUserNameByUnameAndUpsw(u);
			session.setAttribute("currentUserName", currentUserName);
			session.setAttribute("currentRole", r.getRname());
			if(r.getRname().equals("商家")){
				Seller s = sellerservice.getSellerByUid(u.getUid());
				int currentOrder = orderservice.getCountCurrentOrderBySid(s.getSid());
				session.setAttribute("currentOrder", currentOrder);
			}
			req.getRequestDispatcher("main.jsp").forward(req, resp);
		}else{
			session.setAttribute("errorMsg", "用户名或密码错误");
			resp.sendRedirect("login.jsp");
		}
		
	}
}
